import { Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  AsyncValidatorFn,
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  ValidatorFn,
  Validators
} from '@angular/forms';

import { NzUploadFile } from 'ng-zorro-antd/upload';


const getBase64 = (file: File): Promise<string | ArrayBuffer | null> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });

@Component({
  selector: 'app-demo-master',
  templateUrl: './demo-master.component.html',
  styleUrls: ['./demo-master.component.less']
})
export class DemoMasterComponent implements OnInit {

  validateFormData: any = {
    name: '',
    sex: '',
    age: '',
    departmentId: '',
    jcbw: '',
    ultrasoundNumber: '',
    cfz: '',
    datePickerTime: '',
    // 时间-传入格式
    // datePickerTime: new Date('Wed Apr 03 2024 11:40:00 GMT+0800 (中国标准时间)'),
    // datePickerTime: new Date("2024-4-3 11:50:00"),
    csms: '',
    csts: '',
    proposal: '',
    jcys: '',
    bgsj: '',
  }



  // 定义表单数据======================
  validateForm: FormGroup<{
    name: FormControl<string>;
    sex: FormControl<string>;
    age: FormControl<string>;
    departmentId: FormControl<string>;
    jcbw: FormControl<string>;
    ultrasoundNumber: FormControl<string>;
    cfz: FormControl<string>;
    datePickerTime: FormControl<Date | null>;
    csms: FormControl<string>;
    csts: FormControl<string>;
    proposal: FormControl<string>;
    jcys: FormControl<string>;
    bgsj: FormControl<string>;
  }>

  // 配置表单内容以及校验===============
  constructor(private fb: NonNullableFormBuilder) {

    this.validateForm = this.fb.group({
      // name: ['', [required, maxLength(12), minLength(6)], [this.userNameAsyncValidator]],
      name: [this.validateFormData.name, [Validators.required]],
      // name: [''],
      sex: [this.validateFormData.sex],
      age: [this.validateFormData.age],
      departmentId: [this.validateFormData.departmentId],
      jcbw: [this.validateFormData.jcbw],
      ultrasoundNumber: [this.validateFormData.ultrasoundNumber],
      cfz: [this.validateFormData.cfz],
      datePickerTime: this.fb.control<Date | null>(this.validateFormData.datePickerTime),
      csms: [this.validateFormData.csms],
      csts: [this.validateFormData.csts],
      proposal: [this.validateFormData.proposal],
      jcys: [this.validateFormData.jcys],
      bgsj: [this.validateFormData.bgsj],
    });
  }

  ngOnInit(): void {
    // console.log(this.validateForm.value);
    // this.validateForm.setValue({ })
  }

  // 提交
  submitForm(): void {
    // console.log(this.validateForm, 'this.validateForm');
    // console.log(this.validateForm.valid, 'this.validateForm.valid');
    // console.log(this.validateForm.value, 'this.validateForm.value');

    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
    } else {
      console.log('校验失败');
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }

  }

  // 重置
  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
  }

  // 上传
  fileList: NzUploadFile[] = [
    // {
    //   uid: '-1',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // },
    // {
    //   uid: '-2',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // },
    // {
    //   uid: '-3',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // },
    // {
    //   uid: '-4',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // },
    // {
    //   uid: '-xxx',
    //   percent: 50,
    //   name: 'image.png',
    //   status: 'uploading',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // },
    // {
    //   uid: '-5',
    //   name: 'image.png',
    //   status: 'error'
    // }
  ];
  previewImage: string | undefined = '';
  previewVisible = false;

  handlePreview = async (file: NzUploadFile): Promise<void> => {
    if (!file.url && !file['preview']) {
      file['preview'] = await getBase64(file.originFileObj!);
    }
    this.previewImage = file.url || file['preview'];
    this.previewVisible = true;
  };



  xxxdy() {

    //（1）首先获得元素的html内容（这里建议如果有样式最好是用内联样式的方式）
    // var newstr = document.getElementById('myDiv');//得到需要打印的元素HTML

    // console.log(newstr, 'newstr');

    //（2）保存当前页面的整个html，因为window.print()打印操作是打印当前页的所有内容，所以先将当前页面保存起来，之后便于恢复。
    // var oldstr = document.body.innerHTML;//保存当前页面的HTML

    //（3）把当前页面替换为打印内容HTML
    // document.body.innerHTML = newstr;
    // document.body = newstr;

    //（4）执行打印操作
    window.print();

    //（5）还原当前页面
    // document.body.innerHTML = oldstr;

    // window.print()
  }
}
